<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">jeecgboot-demo
      <a-form layout="inline" @submit.prevent="searchList">
        <a-row :gutter="24">

          <a-col :md="6" :sm="12">
            <a-form-item label="厂商名称">
              <a-input placeholder="请输入厂商名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>


          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchList" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!--添加按钮-->
    <div class="table-assign">
      <div>
        <a-button @click="handleAdd"  type="primary" icon="plus">添加厂商</a-button>
        <a-button @click="deleteBatch" v-if="selectedRowKeys.length" style="margin-left: 10px;" type="primary" icon="delete">批量删除</a-button>

        <!-- 添加页面弹框-->
        <a-modal title="添加厂商" width="500px" v-model="visible" @ok="handleOk">
          <a-form :form="form">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="厂家名称">
              <a-input placeholder="请输入厂家名称" v-decorator="['name', insert.name]"
                       :readOnly="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="厂家地址">
              <a-input placeholder="请输入厂家地址" v-decorator="['address', insert.address]"
                       :readOnly="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="首次安装时间">
              <a-date-picker @change="dateChange" showTime v-decorator="['firstInstalledTime', insert.firstInstalledTime]" style="width: 100%;" format="YYYY-MM-DD HH:mm:ss">
                <template slot="renderExtraFooter">
                  extra footer
                </template>
              </a-date-picker>
              <!--<a-input placeholder="请选择首次安装时间" -->
                       <!--:readOnly="disableSubmit"/>-->
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人1">
              <a-input placeholder="请输入联系人1" v-decorator="['contact']"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="电话">
              <a-input placeholder="请输入电话" v-decorator="['contactPhone']"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人2">
              <a-input placeholder="请输入联系人2" v-decorator="['contact2']"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="电话">
              <a-input placeholder="请输入电话" v-decorator="['contactPhone2']"
                       :readOnly="disableSubmit"/>
            </a-form-item>


            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注">
              <a-textarea
                v-decorator="[ 'remark', insert.remark]"
                placeholder="请输入说明内容"
                :autosize="{ minRows: 2, maxRows: 6 }"
              />
            </a-form-item>

          </a-form>
        </a-modal>

        <!-- 编辑页面抽屉-->
        <a-drawer
          title="编辑厂商"
          :width="720"
          @close="onEditClose"
          :visible="visibleEdit"
          :wrapStyle="{height: 'calc(100% - 108px)',overflow: 'auto',paddingBottom: '108px'}"
        >
          <a-form :form="formEdit" layout="vertical" hideRequiredMark>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="厂家名称">
              <a-input placeholder="请输入厂家名称" v-decorator="['name', editValidate.name]"
                       :readOnly="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="厂家地址">
              <a-input placeholder="请输入厂家地址" v-decorator="['address', editValidate.address]"
                       :readOnly="disableSubmit"/>
            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="首次安装时间">
              <a-date-picker @change="dateChange" showTime v-decorator="['firstInstalledTime', editValidate.firstInstalledTime]" style="width: 100%;" format="YYYY-MM-DD HH:mm:ss"/>

            </a-form-item>

            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人1">
              <a-input placeholder="请输入联系人1" v-decorator="['contact',editValidate.contact]"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="电话">
              <a-input placeholder="请输入电话" v-decorator="['contactPhone', editValidate.contactPhone]"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人2">
              <a-input placeholder="请输入联系人2" v-decorator="['contact2', editValidate.contact2]"
                       :readOnly="disableSubmit"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="电话">
              <a-input placeholder="请输入电话" v-decorator="['contactPhone2', editValidate.contactPhone2]"
                       :readOnly="disableSubmit"/>
            </a-form-item>


            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注">
              <a-textarea
                v-decorator="[ 'remark', insert.remark]"
                placeholder="请输入说明内容"
                :autosize="{ minRows: 2, maxRows: 6 }"
              />
            </a-form-item>

          </a-form>
          
          <div
            :style="{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }"
          >
            <a-button :style="{marginRight: '8px'}" @click="onEditClose">
              取消
            </a-button>
            <a-button @click="onCommit(record)" type="primary">提交</a-button>
          </div>
        </a-drawer>
      </div>
    </div>
    <br/>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="small"
        rowKey="id"
        :scroll="{x: 1400 }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="onChange">


        <span slot="action" slot-scope="text, record">
<!--          <a @click="handleEdit(record)" v-has="'user:edit'">编辑</a>-->
<!--          <a-divider type="vertical" v-has="'user:edit'"/>-->
          <a class="a-button" href="javascript:;" @click="handleEdit(record)">编辑</a>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
          <!--<a-dropdown>-->
            <!--<a class="ant-dropdown-link">-->
              <!--更多 <a-icon type="down"/>-->
            <!--</a>-->
            <!--<a-menu slot="overlay">-->
              <!--<a-menu-item>-->
                <!--<a href="javascript:;" @click="handleEdit(record)">编辑</a>-->
              <!--</a-menu-item>-->

              <!--<a-menu-item>-->
                <!--<a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">-->
                  <!--<a>删除</a>-->
                <!--</a-popconfirm>-->
              <!--</a-menu-item>-->
            <!--</a-menu>-->
          <!--</a-dropdown>-->
        </span>


      </a-table>
    </div>
    <!-- table区域-end -->

  </a-card>
</template>

<script>
  import {getManufacturerList, manufacturerAdd, manufacturerDelete, manufacturerEdit, manufacturerDeleteBatch} from '@/api/api';
  import {filterObj} from '@/utils/util';
  import moment from "moment";
  let tableColumns = [
    {
      title: '序号',
      dataIndex: '',
      key: 'rowIndex',
      width: 60,
      align: "center",
      customRender: function (t, r, index) {
        return parseInt(index) + 1;
      }
    },
    {
      title: '厂家名称',
      align: "center",
      dataIndex: 'name',
      width: 120
    },
    {
      title: '厂家地址',
      align: "center",
      width: 100,
      dataIndex: 'address',
    },
    {
      title: '首次安装时间',
      align: "center",
      width: 100,
      dataIndex: 'firstInstalledTime'
    },
    {
      title: '联系人1',
      align: "center",
      width: 120,
      dataIndex: 'contact',
    },
    {
      title: '电话',
      align: "center",
      width: 120,
      dataIndex: 'contactPhone',
    },
    {
      title: '联系人2',
      align: "center",
      width: 120,
      dataIndex: 'contact2',
    },
    {
      title: '电话',
      align: "center",
      width: 120,
      dataIndex: 'contactPhone2',
    }, {
      title: '表数量',
      align: "center",
      width: 120,
      dataIndex: 'amount',
    },
    {
      title: '备注',
      align: "center",
      width: 120,
      dataIndex: 'remark',
    },
    {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: {customRender: 'action'},
      align: "center",
      width: 120,
      fixed: 'right'
    }
  ];
  export default {
    name: "ManufacturerInfo",
    data() {
      return {
        description: '这是厂商信息查询页面',
        columns: tableColumns,
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        visible: false,
        visibleEdit: false,
        disableSubmit: false,
        /* 分页参数 */
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        form: this.$form.createForm(this),
        formEdit: this.$form.createForm(this),
        insert: {
          name: {
            rules: [{required: true, message: '请输入厂家名称!'}]
          },
          firstInstalledTime: {
            rules: [{required: true, message: '请选择首次安装时间!'}]
          },
          address: {
            rules: [{required: false, message: ''}]
          },
          contact: {
            rules: [{required: false, message: ''}]
          },
          contactPhone: {
            rules: [{required: false, message: ''}]
          },
          contact2: {
            rules: [{required: false, message: ''}]
          },
          contactPhone2: {
            rules: [{required: false, message: ''}]
          },
          remark: {
            rules: [{required: false, message: ''}]
          },

        },
        editValidate: {
          name: {
            rules: [{required: true, message: '请输入厂家名称!'}],
            initialValue: ""
          },
          address: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          contact: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          contactPhone: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          contact2: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          contactPhone2: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          remark: {
            rules: [{required: false, message: ''}],
            initialValue: ""
          },
          firstInstalledTime: {
            rules: [{required: true, message: '请选择首次安装时间!'}],
          },
        },
        /* 排序参数 */
        sorter: {
          column: 'createTime',
          order: 'desc',
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys*/
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: "",
        url: {
          list: "/api/v1/iotManufacturer/list",
          add: "/api/v1/iotManufacturer/add",
          edit: "/api/v1/iotManufacturer/edit",
        },
        labelCol: {
          xs: {span: 24},
          sm: {span: 6},
        },wrapperCol: {
          xs: {span: 24},
          sm: {span: 18},
        },
        firstTime: null,
        currentRowId: "",
      }
    },
    created(){
      this.handleDataList(1);
    },
    computed: {},
    methods: {
      moment,
      onChange(pagination, filters, sorter) {
        /* 表格change事件 */

        //分页、排序、筛选变化时触发
        if (Object.keys(sorter).length > 0) {
          this.sorter.column = sorter.field;
          this.sorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.pagination = pagination;
        this.handleDataList();
      },
      handleAdd() {
        this.visible = true;
      },
      handleOk(e) {
        const that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            values.firstInstalledTime = that.firstTime;
            manufacturerAdd(values, (res)=>{
              if(res.code == 200) {
                that.$message.success("添加成功!");
                that.handleDataList();
                that.visible = false;
              }else {
                that.$message.error(res.message);
                that.visible = false;
              }
            })
          }
        })
      },
      edit(record) {
        if (record.id) {
          this.id = record.id;
        }
        this.queryParam = {}
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'itemText', 'itemValue'))
        });
        // 当其它模块调用该模块时,调用此方法加载字典数据
        this.loadData();
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      getQueryParams() {
        var param = Object.assign({}, this.queryParam);
        param.id = this.id;
        param.field = this.getQueryField();
        param.pageNo = this.pagination.current;
        param.pageSize = this.pagination.pageSize;
        return filterObj(param);
      },
      getQueryField() {
        //TODO 字段权限控制
        var str = "id,";
        this.columns.forEach(function (value) {
          str += "," + value.dataIndex;
        });
        return str;
      },
      handleEdit: function (record) {
        this.visibleEdit = true;
        this.currentRowId = record.id;
        for(let index in this.editValidate){
          if(index == "firstInstalledTime"){
            this.editValidate[index].initialValue = moment(record[index], 'YYYY-MM-DD HH:mm:ss')
          }else {
            this.editValidate[index].initialValue = record[index];
          }
        }
      },
      handleDataList(page) {
        /* 表格数据加载 */

        let that = this;

        //加载数据 若传入参数1则加载第一页的内容
        if (page === 1) {
          this.pagination.current = 1;
        }

        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getManufacturerList(params,function (res) {
          if (res.success) {
            that.dataSource = res.result.records;
            that.pagination.total = Number(res.result.total);
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          that.loading = false;
        })
      },
      searchList() {
        this.handleDataList(1);
      },
      searchReset() {
        this.queryParam = {}
        this.handleDataList(1);
      },
      showDrawer() {
        this.visible = true
      },
      onClose() {
        this.visible = false;
        this.form.resetFields();
        // this.dataSource = [];
      },
      onEditClose() {
        this.visibleEdit = false;
      },
      onCommit() {//编辑提交
        const that = this;
        //触发表单验证
        this.formEdit.validateFields((err, values) => {
          if (!err) {
           values.firstInstalledTime = this.firstTime;
           values.id = that.currentRowId;
            manufacturerEdit(values, (res)=>{
              if (res.code == 200) {
                that.$message.success("修改成功!");
                that.visibleEdit = false;
                that.handleDataList();
              }else {
                that.$message.error(res.message);
              }
            })
          }
        })
      },
      handleDelete (id) {
        let that = this;
        manufacturerDelete({id: id}, (res)=>{
          if(res.code == 200) {
            that.$message.success("删除成功!");
            that.handleDataList();
          }else {
            that.$message.error(res.message);
          }
        })
      },
      dateChange(date, dateString) {
        console.log(date, dateString);
        this.firstTime = dateString;
      },
      deleteBatch () {
        let that = this;
        manufacturerDeleteBatch({ids: '' + this.selectedRowKeys}, (res)=>{
          if (res.code == 200) {
            that.$message.success("删除成功!");
            that.handleDataList();
          }else {
            that.$message.error(res.message);
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>